<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/9/21 11:19
 * Desc: 登录
 */
class Service_Api_Member_Login extends Contract_Api_Member_Login
{

    public function login_by_user(array $params): array
    {
        /**
         * @var $user
         * @var $pwd
         * @var $captcha_key
         * @var $code
         */
        extract($params);

        try {
            if (!Model_Api_V2_Common::verify_image_code($captcha_key, $code)) {
                throw new Exception(__("checkcode_error"));
            }

            //用户不存在
            $member = Model_Member::member_find($user);
            if (empty($member)) {
                throw new Exception(__("账号不存在，请先注册"));
            }

            if (empty($member['pwd'])) {
                throw new Exception(__("账号未设置密码"));
            }

            $password = Model_Member::make_pwd($pwd);
            if ($member['pwd'] != $password) {
                throw new Exception(__("密码错误"));
            }

            $data = Model_Api_V2_Member_Login::login_init($member);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }

        // 验证成功后清除图片缓存
        Model_Api_V2_Common::cache('set', $captcha_key, null);

        return $data;
    }


    public function login_by_mini_program(array $params): array
    {
        /**
         * @var $authorizer_appid
         * @var $wxSns
         * @var $code
         */
        extract($params);

        if (empty($authorizer_appid)) {
            //兼容直连
            //微信小程序appid,appsecret
            $config_params = [
                'cfg_global_client_appkey', //小程序appid
                'cfg_global_client_appsecret', //小程序appsecret

            ];
            $wx_configs    = Model_Sysconfig::get_configs(0, $config_params);
            $app_id        = $wx_configs['cfg_global_client_appkey'];
            $app_secret    = $wx_configs['cfg_global_client_appsecret'];
            $wxapi_url     = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
            $wxSns         = sprintf($wxapi_url, $app_id, $app_secret, $code);
        } else {
            $wxSns = urldecode(htmlspecialchars_decode($wxSns));
        }

        $wx_data = json_decode(file_get_contents($wxSns), true);
        if (!$wx_data['openid']) {
            throw new Exception(__("微信登录失败_OPENID"));
        }

        $out                = array();
        $out['openid']      = $wx_data['openid'];
        $out['unionid']     = $wx_data['unionid'] ?? '';
        $out['session_key'] = $wx_data['session_key']; // 新加2018/5/21
        $out['token']       = Common::authcode($wx_data['openid'] . '||' . $wx_data['session_key'], 'ENCODE');

        $litpic   = '';// 用户头像每次登陆时重新更新
        $nickname = '';// 用户头像每次登陆时重新更新
        $result   = Model_Api_V2_Member_Wechat_Login::get_member_by_mini_openid($wx_data['openid'], $litpic, $nickname);
        if ($result['status']) {
            if ($out['unionid']) {
                // 更新微信小程序三方openid
                DB::update('member_third')
                    ->set(array('openid' => $out['unionid']))
                    ->where("wx_mini_openid", "=", $wx_data['openid'])
                    ->execute();
            }
            $result['data']['wx_data'] = $out;
        } else { // 用户不在系统里面 需要后续的注册登陆流程
            $result = array('status' => true, 'msg' => '需要进行登录', 'data' => array('wx_data' => $out, 'token' => false));
        }

        return $result;
    }

    public function get_phone_by_mini_program(array $params): array
    {
        /**
         * @var $authorizer_appid
         * @var $sessionKey
         * @var $encryptedData
         * @var $iv
         */
        extract($params);

        include_once BASEPATH . "/plugins/api/vendor/xcx/wxBizDataCrypt.php";
        if (empty($authorizer_appid)) {
            //微信小程序appid
            $authorizer_appid = Model_Sysconfig::get_configs(0, 'cfg_global_client_appkey', true);
            if (!$authorizer_appid) {
                throw new Exception('微信小程序未配置');
            }
        }

        // 去掉获取到iv的值中间有空格
        $new_iv  = str_replace(' ', '', $iv);
        $pc      = new WXBizDataCrypt($authorizer_appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $new_iv, $data);
        if ($errCode != 0) {
            throw new Exception('获取手机信息失败_' . $errCode);
        }

        return json_decode($data, true);
    }


    public function login_by_toutiao(array $params): array
    {
        /**
         * @var $code
         * @var $user_info
         */
        extract($params);

        $user_info = json_decode($user_info, true);
        if (!is_array($user_info)) {
            throw new Exception(__("获取用户信息失败"));
        }

        // 获取openid
        $config = Model_Sysconfig::get_configs(0, array('cfg_toutiao_appid', 'cfg_toutiao_secret'), 0);
        if (empty($config['cfg_toutiao_appid']) || empty($config['cfg_toutiao_secret'])) {
            throw new Exception(__("小程序 app_id 或 secret 未配置"));
        }

        $appid  = $config['cfg_toutiao_appid'];
        $secret = $config['cfg_toutiao_secret'];
        $url    = sprintf('https://developer.toutiao.com/api/apps/jscode2session?appid=%s&secret=%s&code=%s', $appid, $secret, $code);
        $return = json_decode(file_get_contents($url), true);

        if (empty($return['openid'])) {
            $err_msg = $return['errmsg'] ? "TT_ERROR[{$return['errmsg']}]" : __("登录失败_OPENID");
            throw new Exception($err_msg);
        }

        $out                = array();
        $out['openid']      = $return['openid'];
        $out['session_key'] = $return['session_key']; //
        $out['token']       = Common::authcode($return['openid'] . '||' . $return['session_key'], 'ENCODE');

        $litpic   = $user_info['avatarUrl'];
        $nickname = $user_info['nickName'];
        $result   = Model_Api_V2_Member_Toutiao_Login::get_member_by_tt_openid($return['openid'], $litpic, $nickname);
        if ($result['status']) {
            $result['data']['wx_data'] = $out;
        } else { // 用户不在系统里面 需要后续的注册登陆流程
            $result = array('status' => true, 'msg' => '需要进行登录', 'data' => array('wx_data' => $out, 'token' => false));
        }

        return $result;
    }

    public function get_phone_by_toutiao_program(array $params): array
    {
        /**
         * @var $sessionKey
         * @var $encryptedData
         * @var $iv
         */
        extract($params);
        //获取头条配置
        $config = Model_Sysconfig::get_configs(0, array('cfg_toutiao_appid'), 0);
        if (empty($config['cfg_toutiao_appid'])) {
            throw new Exception(__("小程序 app_id 未配置"));
        }

        $appid = $config['cfg_toutiao_appid'];

        // 去掉获取到iv的值中间有空格
        include_once BASEPATH . "/plugins/api/vendor/xcx/wxBizDataCrypt.php";
        $new_iv  = str_replace(' ', '', $iv);
        $pc      = new WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $new_iv, $data);

        // 记录手机获取状态
        $log = array(
            'time' => date('Y-m-d H:i:s', time()),
            'data' => $data,
            'errCode' => $errCode,
            'iv' => $iv,
            'new_iv' => $new_iv,
            'encryptedData' => $encryptedData,
            'sessionKey' => $sessionKey,
            'appid' => $appid
        );
        St_Log::write('字节手机号获取', $log, 'toutiao/log');

        if ($errCode != 0) {
            throw new Exception('获取手机信息失败_' . $errCode);
        }

        return json_decode($data, true);
    }

    public function login_by_alipay(array $params): array
    {
        /**
         * @var $authCode
         * @var $avatar
         * @var $nickName
         */
        extract($params);

        $config_varname = array(
            'cfg_zhifubao_alipay_appid',
            'cfg_zhifubao_alipay_private_key',
            'cfg_zhifubao_alipay_public_key'
        );
        $config         = Model_Sysconfig::get_configs(0, $config_varname, 0);
        if (empty($config['cfg_zhifubao_alipay_appid']) || empty($config['cfg_zhifubao_alipay_private_key']) || empty($config['cfg_zhifubao_alipay_public_key'])) {
            throw new Exception(__("支付宝配置信息未配置"));
        }

        include BASEPATH . 'plugins/zhifubao/classes/vendor/Alipay/AopClient.php';
        include BASEPATH . 'plugins/zhifubao/classes/vendor/Alipay/request/AlipaySystemOauthTokenRequest.php';

        $aop                     = new AopClient();
        $aop->gatewayUrl         = 'https://openapi.alipay.com/gateway.do';
        $aop->appId              = $config['cfg_zhifubao_alipay_appid'];
        $aop->rsaPrivateKey      = $config['cfg_zhifubao_alipay_private_key'];
        $aop->alipayrsaPublicKey = $config['cfg_zhifubao_alipay_public_key'];
        $aop->apiVersion         = '1.0';
        $aop->signType           = 'RSA2';
        $aop->postCharset        = 'UTF-8';
        $aop->format             = 'json';

        $request = new AlipaySystemOauthTokenRequest();
        $request->setGrantType("authorization_code");
        $request->setCode($authCode);
        $return = $aop->execute_get_userid($request);

        if (!$return['user_id']) {
            throw new Exception('获取userid失败');
        }

        $data = Model_Api_V2_Member_Zhifubao_Login::get_member_by_zfb_openid($return['user_id'], $avatar, $nickName);
        if ($data['status']) {
            $result = array('zfb_data' => $return, 'memberInfo' => $data['data']['memberInfo'], 'token' => $data['data']['token']);
        } else {
            // 用户不在系统里面 需要后续的注册登陆流程
            $result = array('zfb_data' => $return, 'token' => false);
        }

        return $result;
    }

    public function login_by_phone(array $params): array
    {
        $come_from = $params['comefrom'];
        switch ($come_from) {
            case 'wechat':
                $result = Model_Api_V2_Member_Wechat_Login::login_by_phone($params);
                break;
            case 'h5':
                $result = Model_Api_V2_Member_Wap_Login::login_by_phone($params);
                break;
            case 'toutiao':
                $result = Model_Api_V2_Member_Toutiao_Login::login_by_phone($params);
                break;
            case 'zhifubao':
                $result = Model_Api_V2_Member_Zhifubao_Login::login_by_phone($params);
                break;
            default:
                $result = array('status' => false, 'msg' => '提交信息有误');
                break;
        }
        $rank = Model_Member::member_rank($result['data']['mid'], array('return' => 'all'));
        $result['data']['memberinfo']['rank_name'] = $rank['rankname'];
        $result['data']['memberinfo']['rank']      = $rank['current'];

        return $result;
    }
}